import { NestExpressApplication } from '@nestjs/platform-express'
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'
import { Logger, ValidationPipe, VersioningType } from '@nestjs/common'
import { PostInterceptor } from './common/response'
import { HttpExceptionFilter } from './common/filter'
import { join } from 'path'
import * as session from 'express-session'

import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
export const setupApp = (app: NestExpressApplication) => {
  const middlewareAll = (req: Request, res: Response, next: any) => {
    next()
  }
  // 全局拦截器
  app.useGlobalPipes(
    new ValidationPipe({
      // 去除在类上不存在的字段
      whitelist: true
    })
  )
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER))
  app.setGlobalPrefix('/api/v1')
  app.enableVersioning({
    type: VersioningType.URI
  })
  app.useGlobalInterceptors(new PostInterceptor())
  app.use(middlewareAll)
  const logger = new Logger()
  app.useGlobalFilters(new HttpExceptionFilter(logger))
  app.useStaticAssets(join(__dirname, '..', 'public'), {
    prefix: '/static'
  })
  app.use(
    session({
      secret: 'keyboard cat',
      name: 'willes.session',
      rolling: true,
      cookie: { maxAge: null }
    })
  )
  const options = new DocumentBuilder().setTitle('API文档').addBearerAuth().setDescription('demo setDescription').setVersion('1').build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('/api-doc', app, document)
}
